package cn.wolfcode.user.servlet;

import cn.wolfcode.user.domain.User;
import cn.wolfcode.user.service.UserService;
import cn.wolfcode.user.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class UserServlet extends HttpServlet {
    private static final int ONE_WEEK = 1000 * 60 * 60 * 24 * 7;
    private UserService userService = new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
//        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String randomCode = req.getParameter("randomCode");
        String RANDOMCODE_IN_SESSION = (String) req.getSession().getAttribute("RANDOMCODE_IN_SESSION");
        if (!(randomCode != null && randomCode != "" && randomCode.equalsIgnoreCase(RANDOMCODE_IN_SESSION))) {
            req.setAttribute("logMsg","验证码输入错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }
        try {
            User user = userService.check(username, password);
            boolean flag = Boolean.parseBoolean(req.getParameter("rememberMe"));
            Cookie cookie = new Cookie("username", user.getUsername());
            if (flag) {
                cookie.setMaxAge(ONE_WEEK);
            }else {
                cookie.setMaxAge(0);
            }
            resp.addCookie(cookie);
            req.getSession().setAttribute("USER_IN_SESSION", user);
            resp.sendRedirect("/student");
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("logMsg","用户名或密码输入错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }
}
